<?php

declare(strict_types=1);

namespace App\CustHub\Listener;

use App\CustHub\Event\ChOperation;
use App\CustHub\Event\ChOperationLog;
use App\CustHub\Interfaces\ChOperLogServiceInterface;
use App\CustHub\Mapper\ChOperationLogMapper;
use Carbon\Carbon;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;

#[Listener]
class ChOperationLogListener implements ListenerInterface
{
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * @return string[] returns the events that you want to listen
     */
    public function listen(): array
    {
        return [ChOperationLog::class];
    }

    /**
     * Handle the Event when the event is triggered, all listeners will
     * complete before the event is returned to the EventDispatcher.
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function process(object $event): void
    {
        $logData = $event->logData->toArray();
        $mapper = $this->container->get(ChOperationLogMapper::class);

        $logData['created_at'] = Carbon::now()->toDateTimeString();
        $model = $mapper->model::create($logData);

        if($model && !empty($logData['robotIds'])){
            $model->robots()->sync($logData['robotIds']);
        }
    }
}